package com.studentstreet.tools;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

public class HttpHelper {
	// 连接超时时间:5秒
	private static final int REQUEST_TIMEOUT = 5 * 1000;
	// 设置等待数据传送超时时间：10秒钟
	private static final int SO_TIMEOUT = 10 * 1000;
	// url
	private String url = "";
	// 请求参数列表
	private List<NameValuePair> params = null;

	public HttpHelper(String url) {
		super();
		this.url = url;
		params = new ArrayList<NameValuePair>();
	}

	public void addParam(String key, String value) {
		params.add(new BasicNameValuePair(key, value));
	}

	// 取得服务器返回的数据
	public String getResponse() {
		String responseStr = "";
		// 使用apache HTTP客户端实现
		HttpPost request = new HttpPost(url);
		try {
			// 设置请求参数项，以UTF-8编码方式发送
			request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
			// 设置网络连接的基本参数
			BasicHttpParams httpParams = new BasicHttpParams();
			// 设置超时时间
			HttpConnectionParams.setConnectionTimeout(httpParams,
					REQUEST_TIMEOUT);
			HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
			HttpClient client = new DefaultHttpClient(httpParams);

			// 获得服务器的返回参数
			HttpResponse response = client.execute(request);
			// HttpStatus.SC_OK:200 表示请求成功
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				// 获得获得服务器的响应字符串-->用户Json数据
				responseStr = EntityUtils.toString(response.getEntity());
			}
		} catch (Exception e) {
			// 网络出错
			e.printStackTrace();
			return "";
		}
		return responseStr;
	}
}
